import axios from 'axios'
import type { User, CreateUserRequest, UpdateUserRequest } from '../types/user'

const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// API 响应类型定义
interface ApiResponse<T> {
  success: boolean
  data: T
  message?: string
}

export const userApi = {
  // 获取所有用户
  async getUsers(): Promise<User[]> {
    const response = await api.get<ApiResponse<User[]>>('/users')
    return response.data.data
  },

  // 获取单个用户
  async getUser(id: number): Promise<User> {
    const response = await api.get<ApiResponse<User>>(`/users/${id}`)
    return response.data.data
  },

  // 创建用户
  async createUser(user: CreateUserRequest): Promise<User> {
    const response = await api.post<ApiResponse<User>>('/users', user)
    return response.data.data
  },

  // 更新用户
  async updateUser(id: number, user: UpdateUserRequest): Promise<User> {
    const response = await api.put<ApiResponse<User>>(`/users/${id}`, user)
    return response.data.data
  },

  // 删除用户
  async deleteUser(id: number): Promise<void> {
    await api.delete(`/users/${id}`)
  }
}
